<template>
  <view class="content">
    <view class="page-body">
      <view class="main">
        <!-- <image class="img" src="../../static/profile/bg.png"></image> -->
        <view class="title">
          工作台
        </view>
        <view class="box" @click="clickSign">
          <image src="../../static/index/clock.png" mode="aspectFit" :class="`textBg ${(!is || errTime) && 'no'}`"></image>
          <view class="text">
            <view class="curTime">
              {{time.slice(0, 5)}}
            </view>
            <view class="mark">
              {{showText}}
            </view>
          </view>
        </view>
        <view v-if='currentAddress && !errTime && is' class="currentAddress">当前位置: <text>{{currentAddress}}</text></view>
        <view v-else class="currentAddress"> </text></view>
        <view v-if='loading === false && is === false' class="currentAddress">不再打卡范围内</view>
        <view v-if='loading === false && is === null' class="currentAddress">定位失败，请刷新重试</view>
      </view>

    </view>


    <homeGrid />
    <view class="reload" @click='relocation'>
      <uni-icons type='reload' size="30" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script>
  import md5 from 'js-md5'
  import {
    jsonp
  } from 'vue-jsonp'

  import mainHead from "@/components/mainHead/index.vue"
  import homeGrid from "@/components/homeGrid/index.vue"
  import {
    formateDate,
    pointInsideCircle,
    isSameDay
  } from "./time.js"
  import {
    handleSignClick,
    setSignInfo,
    addSignInfo,
    getSignInfo,
    delSignInfo,
    getInfo,
    singKey
  } from "./utils.js"
  import {
    BASE_LOCATION_URL
  } from '../../utils/request.js'
  import {
    getClockConfig,
    log,
    setClockIn
  } from '../../utils/api.js'
import { messageSuccess } from '../../utils/index.js'
  export default {
    components: {
      mainHead,
      homeGrid
    },
    computed: {
      showText() {
        if(this.userClockInfo.clockOutStatus == 0) {
          return '早退打卡'
        }
        if (this.errTime) {
          return '未打卡'
        }

        if (this.isAm && this.isPm) {
          return '打卡已完成'
        }
        if (this.isAm) {
          return '下班打卡'
        }

        if(!this.loading && !this.is) {
          return ' '
        }
        if (!this.Am) {
          return '上班打卡'
        }
        return '下班打卡'
      },
      errTime() {
        const now = +new Date()
        const outTime = +new Date(this.customConfig.day + ' ' + this.commonConfig.clockOut)

        if (!this.isAm && now > outTime) {
          return true
        }
        return false
      }
    },
    data() {
      return {
        hasLoaded: false,
        currentAddress: '',
        name: "",
        moduleColor: 'CBlue',
        moduleTitle: '上班打卡',
        bzText: {
          time: "",
          address: "",
          img: "",
          remarks: ""
        },
        type: "",
        achievement: {
          money: "888.88",
          num: "1"
        }, //业绩	
        r: 80, //半径

        isAm: false, //上班是否打卡
        isPm: false, //下班是否打卡

        is: null, //是否正常打卡（外勤打卡）
        time: formateDate(new Date(), 'h:min:s'), //当前时分秒
        date: formateDate(new Date(), 'Y-M-D'),
        week: "", //当前星期几			
        latitude: "", //当前经度
        longitude: "", //当前维度
        address: "定位中...", //
        wqInfo: null,
        allSign: [], //所有打卡信息		
        organize: '', //考情组						
        signInfo: {
          mode: "",
          latitude: "",
          longitude: "",
          address: "",
          time: "",
          remarks: ""
        }, //打卡信息 （模式，经纬度，地址，时间）
        covers: [
          // 公司点信息
          {
            id: 0,
            callout: {
              content: "",
              color: "",
              display: "",
            },
            latitude: 113224630.115,
            longitude: 1837131905.02,
            iconPath: '../../../static/index/location.png'
          },
        ],
        circles: [
          // 公司圆信息(latitude:13224630.115,longitude:3731905.02,);
          {
            latitude: 13224630.115,
            longitude: 131731905.02,
            radius: 80,
            strokeWidth: 1,
            fillColor: "#7fff0099"
          },
        ],
        userClockInfo: {},
        customConfig: {isNeedClock: -1},
        commonConfig: {},
        loading: true
      }
    },
    // 初始化
    onLoad() {
      this.getClockConfigInfo()

    },
    methods: {
      isAmTime() {
        var hours = new Date().getHours(); // 获取小时数
        return hours < 12
      },
      isPmTime() {
        var hours = new Date().getHours(); // 获取小时数
        return hours >= 12
      },
      async getClockConfigInfo() {
        // 初始化数据  （公司的经纬度 公司名称 打卡范围 ）
        const {
          customConfig,
          userClockInfo,
          commonConfig
        } = await getClockConfig()
        this.customConfig = customConfig
        this.commonConfig = commonConfig
        this.covers[0].callout.content = commonConfig.clockLocationAddress;
        this.covers[0].latitude = this.circles[0].latitude = commonConfig.clockLocationLatitude;
        this.covers[0].longitude = this.circles[0].longitude = commonConfig.clockLocationLongitude;
        this.r = this.circles.radius = commonConfig.clockRadius;
        this.userClockInfo = userClockInfo || {}
        if (this.userClockInfo.clockInRealTime && this.userClockInfo.clockOutStatus == 1) {
          this.isAm = true
          this.isPm = true
          this.loading = false
          this.moduleTitle = '打卡完成'
          this.moduleColor = 'CBlue'
          return
        }
        if (this.userClockInfo.clockInRealTime) {
          this.isAm = true
        }
        if (this.userClockInfo.clockOutStatus == 1) {
          this.isPm = true
        }
        this.getLocation();
      },
      getWeekDate() {
        var now = new Date();
        var day = now.getDay();
        var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
        this.week = weeks[day];
      },
      togglePopup(type) {
        this.type = type;
      },
      // 腾讯位置服务
      getAdd() {
        if (this.isAm && this.isPm) {
          return;
        }
        var that = this;


        jsonp('https://apis.map.qq.com/ws/geocoder/v1/?', {
          location: this.latitude + ',' + this.longitude, // 经纬度
          callbackQuery: 'callback',
          callbackName: 'jsonpCallback',
          key: singKey, 
          output: 'jsonp', // output必须jsonp   不然会超时
        }).then((res) => {
          console.log(res, 99)
          // 获取到的res 就是继续的地址的所有信息;
          var data = res.result;

          if (that.is === null) {
            that.address = "请检查位置信息！";
          }
          let address = res.result.address + res.result.formatted_addresses.recommend
          that.currentAddress = address;
          that.signInfo.address = address;
        }).catch(err => {
          uni.showModal({
            title: 'tecent err',
            content: JSON.stringify(err)
          })
        })

  },

  // 重新定位
  relocation() {
      this.getLocation();
      // uni.navigateTo({url:"/pages/sign/sign",})
    },


    // 显示备注
    showBz(type) {
      this.type = 'middle-list';
      if (type == 'amSign') {
        this.bzText.time = this.amSign.time;
        this.bzText.address = this.amSign.address;
        this.bzText.remarks = this.amSign.remarks;
      } else if (type == 'pmSign') {
        this.bzText.time = this.pmSign.time;
        this.bzText.address = this.pmSign.address;
        this.bzText.remarks = this.pmSign.remarks;
      }
    },

    // 获取当前位置
    getLocation() {
      var that = this;

      uni.showToast({
        title: '定位中...',
        icon: 'loading',
        mask: true
      })
      this.loading = true
      uni.getLocation({
        type: 'wgs84', //返回可以用于uni.openLocation的经纬度
        isHighAccuracy: true,
        success(res) {
          jsonp(`https://apis.map.qq.com/ws/coord/v1/translate`, {
            locations: res.latitude + ',' + res.longitude, 
            callbackQuery: 'callback',
            callbackName: 'jsonpCallback',
            key: singKey, 
            type: 1,
            output: 'jsonp',
          }).then(result => {
                    uni.hideLoading();
                    that.latitude = result.locations[0].lat;
                    that.longitude = result.locations[0].lng;
                    that.covers[1] = {
                      id: 1,
                      latitude: that.latitude,
                      longitude: that.longitude,
                      iconPath: '../../static/index/location.png'
                    }
                    var s = pointInsideCircle([that.latitude, that.longitude], [that.circles[0].latitude, that.circles[0]
                      .longitude
                    ], that.r / 100000);
              
                    that.is = s;
                    that.signInfo.latitude = that.latitude;
                    that.signInfo.longitude = that.longitude;
                    that.signInfo.mode = s ? "正常打卡" : "外勤打卡";
                    that.getAdd()
          }).catch(console.log)

        },
        fail(err) {
          uni.hideLoading();
          that.address = "请检查位置信息"
          uni.showToast({
            title: "请检查位置信息状态！",
            icon: "none",
            mask: true,
            duration: 3000
          })
        },
        complete() {
          uni.hideLoading()
          that.loading = false
        }
      });
    },
    // 点击打卡
    async clickSign() {
        if (this.userClockInfo.clockInRealTime && this.userClockInfo.clockOutStatus == 1) {
          return
        }
        if (this.errTime) return
        if (!this.is) return
        var that = this;
        var isTrue = this.is;
        if (isTrue === null) {
          uni.showToast({
            title: "请检查位置信息状态！",
            icon: "none",
            mask: true,
            duration: 3000
          })
          return;
        }

        this.signInfo.time = formateDate(new Date(), 'Y-M-D h:min:s');
        var a = getSignInfo();
        if (a != undefined) {
          addSignInfo(getInfo(this.signInfo), a)
        } else {
          setSignInfo(getInfo(this.signInfo))
        }
        const clockType = this.isAm ? 2 : 1
        await setClockIn({
          clockType
        })
        messageSuccess(clockType == 1 ? '上班' : '下班' + '打卡成功', () => {
          this.getClockConfigInfo()
        })
        log({
          address: this.currentAddress,
          curTime: +new Date()
        })
        
        var sign = getSignInfo().main;
        that.allSign = sign.reverse();
        that.isSign = true;

        if (that.isAm === false) {
          that.isAm = true;
          that.amSign = that.allSign[0];
        } else {
          that.isPm = true;
          that.pmSign = that.allSign[1];
        }
      },
      // getStorageSize:function(){
      // 			let that = this;
      // 			uni.getStorageInfo({
      // 				success(res) {
      // 					//console.log(res.keys);
      // 					//console.log(res.limitSize);
      // 					let size = res.currentSize;
      // 					if (size < 1024) {
      // 						that.storageSize = size + ' B';
      // 					} else if (size/1024>=1 && size/1024/1024<1) {
      // 						that.storageSize = Math.floor(size/1024*100)/100 + ' KB';
      // 					} else if (size/1024/1024>=1) {
      // 						that.storageSize = Math.floor(size/1024/1024*100)/100 + ' M';
      // 					}
      // 				}
      // 			})
      // 		},
      // 		clearStorage:function (){
      // 			let that = this;
      // 			uni.showModal({
      // 				title:'提示',
      // 				content:'确定清除缓存吗?',
      // 				confirmText:'立即清除',
      // 				success(res) {
      // 					if(res.confirm){
      // 						uni.clearStorageSync();
      // 						//重新获取并显示清除后的缓存大小
      // 						that.getStorageSize();
      // 						uni.showToast({
      // 							title:'清除成功'
      // 						})
      // 					}
      // 				}
      // 			})
      // 		}
  },
  }
</script>

<style lang="scss">
  .main {
    height: 60vh;
    background-image: linear-gradient(to right, #2858ff, #1ca0ff);
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-around;
  }
  .reload {
    position: fixed;
    right: 20rpx;
    bottom: 120rpx;
    border-radius: 50%;
    background-color: #1ca0ff;
    padding: 12rpx;
  }

  .title {
    color: #fff;
    font-size: 48rpx;
    padding-top: 80rpx;
  }

  .box {
    position: relative;
    width: 272rpx;
    height: 272rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .textBg {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;

      &.no {
        filter: grayscale(0.5);
      }
    }

    .text {
      position: relative;
      display: flex;
      flex-direction: column;

      .curTime {
        font-size: 64rpx;
        color: #fff;
        text-align: center;
      }

      .mark {
        font-size: 30rpx;
        color: #eee;
        text-align: center;
        padding-top: 12rpx;
      }
    }
  }

  .currentAddress {
    font-size: 30rpx;
    color: #eee;
    text-align: center;
    padding: 0 36rpx;
  }


  .map {
    width: 100%;
    height: 260px;
  }

  .uni-list-cell-left {
    padding: 0 30upx;
  }

  .text-desc {
    display: flex;
    justify-content: space-between;
    padding: 10upx 20upx
  }

  .colorRed {
    color: red;
  }

  .colorGreen {
    color: #32CD32;
  }

  .colorYellow {
    color: yellow;
  }

  .colorBlue {
    color: #007aff;
  }

  .bgBlue {
    background-color: #007aff;
  }

  .bgGreen {
    background-color: #32CD32;
  }

  .bgAsh {
    background-color: #C8C7CC;
  }

  .uni-timeline {
    padding: 30upx 20upx;
  }

  .uni-timeline-item-content-t {
    font-weight: bold;
  }

  .desc-pad {
    padding: 0 0upx
  }

  .desc-pad .bz {
    color: rgb(0, 122, 255);
  }

  .desc-pad .bz .icon {
    color: rgb(0, 122, 255)
  }

  .uni-timeline-last-item .uni-timeline-item-divider {
    background: #bbb;
  }

  .CBlue {
    background-color: #007aff;
    box-shadow: 0 3px 3px #007aff;
  }

  .CGreen {
    background-color: #32CD32;
    box-shadow: 0 3px 3px #32CD32;
  }

  .CYellow {
    background-color: #FFA500;
    box-shadow: 0 3px 3px #FFA500;
  }

  .CAsh {
    background-color: #C8C7CC;
    box-shadow: 0 3px 3px #C8C7CC;
  }

  .module {
    overflow: hidden;
    margin: 20upx auto;
    width: 220upx;
    height: 220upx;
    border-radius: 50%;
    color: #fff;
    text-align: center;
  }

  .module .text {
    font-size: 20px;
    margin: 50upx auto 10upx;
  }

  .uni-timeline-item .uni-timeline-item-content {
    width: 100%;
    padding-right: 20upx;
  }

  .content-show {
    width: 100%
  }



  .mgsBox {
    padding: 20upx;
    margin-bottom: 30upx;
    border-radius: 8upx;
    background-color: #f1f1f1;
  }

  .iswqbox {
    display: flex;
    align-items: center;
  }

  .iswq {
    width: 100upx;
    margin-left: 10upx;
  }
</style>